package org.feichao.imagegenerator;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 图片合成工具, 支持多图层
 * @author zhangzc@djcars.cn
 * @create 2016/8/9
 */
public class ImageBuilder {

    //画板
    public BufferedImage canvas;

    //素材列表
    private List<Drawable> drawableList =  new ArrayList();

    //上下文
    private Context context = new Context();

    private ImageBuilder(){

    }

    private ImageBuilder(BufferedImage canvas){
        this.canvas = canvas;
    }

    /**
     * 默认画板
     * @param canvas
     * @return
     */
    public static ImageBuilder create(BufferedImage canvas){
        ImageBuilder builder = new ImageBuilder(canvas);
        builder.context.canvas = builder.canvas;
        return builder;
    }

    /**
     * 生成默认画板
     * @param width
     * @param height
     * @param color
     * @return
     */
    public static ImageBuilder create(int width, int height, Color color){
        ImageBuilder builder = new ImageBuilder();
        builder.canvas = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D dg = builder.canvas.createGraphics();
        dg.setColor(color);//设置笔刷白色
        dg.fillRect(0,0,width,height);//填充整个屏幕
        dg.dispose();

        builder.context.canvas = builder.canvas;

        return builder;
    }

    /**
     * 添加图层,图层添加的顺序决定了覆盖顺序, 先添加的图层会被后添加的图层覆盖
     * @param drawable 素材
     * @return
     */
    public ImageBuilder addLayer(Drawable drawable){
        drawableList.add(drawable);
        return this;
    }

    /**
     * 合成并输出文件
     * @param file
     * @throws IOException
     */
    public void build(File file) throws Exception {
        for(Drawable drawable: drawableList){
            try {
                drawable.doDraw(context);
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("Failed to ImageBuilder.build: " + file.getAbsolutePath(), e);
            }
        }

        ImageIO.write(canvas, "png", file);//写图片
    }


}
